<script setup lang="ts">
import {
  parkDelEnApi,
  parkDelRentApi,
  parkEnOutRentApi,
  parkEnRentApi,
  parkGetBusinessLicenseApi,
  parkGetEnListApi,
  parkGetEnRentListApi,
  parkGetRentBuildingListApi,
} from '@/apis/park'
import type {
  enListItem,
  enListParams,
  EnRentBuildingI,
  EnRentI,
  EnRentParamsI,
} from '@/types/park'
import { formatRentStatus, formatTagType } from '@/utils/format'
import {
  ElMessage,
  ElMessageBox,
  type UploadRequestOptions,
} from 'element-plus'
import { ref } from 'vue'

/**
 * 企业信息表格
 */
// 参数
let params = ref<enListParams>({
  name: '',
  page: 1,
  pageSize: 8,
})
// 企业列表
let enList = ref<enListItem[]>([])
// 总条数
let total = ref(0)
// 获取企业列表并动态添加租赁合同列表
const getEnListData = async () => {
  const res = await parkGetEnListApi(params.value)
  enList.value = res.rows.map((item) => {
    return {
      ...item,
      rentList: [],
    }
  })
  total.value = res.total
}
getEnListData()
// 搜索区域
const onSearch = () => {
  params.value.page = 1
  getEnListData()
}
// 页码改变
const handleCurrentChange = (val: number) => {
  params.value.page = val
  getEnListData()
}
// 每页条数改变
const changePageSize = (val: number) => {
  params.value.page = 1
  params.value.pageSize = val
  getEnListData()
}
// 删除企业
const deleteEn = async (id: string) => {
  await ElMessageBox.confirm('您确定要删除该企业信息吗?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  await parkDelEnApi(id)
  ElMessage.success('删除成功~')

  if (enList.value.length === 1 && params.value.page > 1) {
    params.value.page--
  }
  getEnListData()
}
/**
 * 租赁合同信息表格
 */
// 给企业添加对应的租赁合同列表
const enAddRentList = async (id?: number) => {
  if (id) {
    const res = await parkGetEnRentListApi(id)
    res.forEach((item) => {
      item.enId = id
    })

    enList.value.forEach((item) => {
      if (item.id === id) {
        item.rentList = res
      }
    })
  }
}
// 表格展开时获取租赁合同列表
const expandHandle = async (row: enListItem) => {
  enAddRentList(row.id)
}
// 退租租赁合同
const outRent = async (id: number, enId: number) => {
  await ElMessageBox.confirm('您确定要退租该合同吗?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  await parkEnOutRentApi(id)
  ElMessage.success('退租成功~')
  // 重新获取该企业租赁合同列表
  enAddRentList(enId)
}
// 删除租赁合同
const delRent = async (id: number, enId: number) => {
  await ElMessageBox.confirm('您确定要删除该合同吗?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  await parkDelRentApi(id)
  ElMessage.success('删除成功~')
  enAddRentList(enId)
}
// 续约租赁合同
const continueRent = async (row: EnRentI) => {
  // 确定合同类型 | 楼宇id | 开始日期 | 企业id
  await getRentBuildingList()
  rentBuildingList.value.push({
    id: row.buildingId as number,
    name: row.buildingName as string,
  })
  rentParams.value.type = 1
  rentParams.value.enterpriseId = row.enId
  rentParams.value.buildingId = row.buildingId
  rentParams.value.endTime = row.endTime
  dialogVisible.value = true
}
/**
 * 添加/续约合同 弹层
 */
// 打开添加合同弹层
const openRentDialog = (id: number) => {
  dialogVisible.value = true
  rentParams.value.enterpriseId = id
  rentParams.value.type = 0
  getRentBuildingList()
}
let dialogVisible = ref(false)
let defaultRentParams: EnRentParamsI = {
  buildingId: undefined,
  startTime: '',
  endTime: '',
  contractUrl: '', // 合同附件url
  contractId: undefined, // 合同附件id
  type: 0, // 类型 0添加 1续约
  enterpriseId: undefined, // 企业id
  dateList: [''],
}
// 添加/续约租赁合同参数
let rentParams = ref<EnRentParamsI>({
  buildingId: undefined,
  startTime: '',
  endTime: '',
  contractUrl: '', // 合同附件url
  contractId: undefined, // 合同附件id
  type: 0, // 类型 0添加 1续约
  enterpriseId: undefined, // 企业id
  dateList: [''],
})
// 租赁合同表单验证规则
const rentRules = {
  buildingId: [{ required: true, message: '请选择租赁楼宇', trigger: 'blur' }],
  dateList: [{ required: true, message: '请选择日期', trigger: 'blur' }],
  contractId: [{ required: true, message: '请上传租赁合同', trigger: 'blur' }],
}
let rentFormRef = ref()
// 可租赁楼宇列表
let rentBuildingList = ref<EnRentBuildingI[]>([])
const getRentBuildingList = async () => {
  rentBuildingList.value = await parkGetRentBuildingListApi()
}
// 日期选择器
const disabledDate = (time: Date) => {
  const ableDate = rentParams.value.endTime

  if (ableDate) {
    return time.getTime() < new Date(ableDate).getTime()
  }

  return false
}
// 上传文件
const upload = ref()
const uploadRequest = async (options: UploadRequestOptions) => {
  const { file } = options
  const formData = new FormData()
  formData.append('file', file)
  formData.append('type', 'contract')
  const res = await parkGetBusinessLicenseApi(formData)
  rentParams.value.contractId = res.id
  rentParams.value.contractUrl = res.url
  // 单独校验表单，如果校验成功，自动清除错误信息
  rentFormRef.value.validateField('contractId')
}
// 移除文件
const removeFile = () => {
  upload.value.clearFiles()
  rentParams.value.contractId = undefined
}
// 合同弹层确定点击事件
const rentDialogConfirm = async () => {
  await rentFormRef.value.validate()
  // 整理参数
  rentParams.value.startTime = rentParams.value.dateList?.[0]
  rentParams.value.endTime = rentParams.value.dateList?.[1]
  rentParams.value.dateList = undefined
  await parkEnRentApi(rentParams.value)
  // 用户提示
  rentParams.value.type === 0
    ? ElMessage.success('添加合同成功~')
    : ElMessage.success('续约成功~')
  // 重新获取该企业租赁合同列表
  enAddRentList(rentParams.value.enterpriseId)
  // 收尾
  rentDialogCancel()
}
// 合同弹层取消点击事件
const rentDialogCancel = () => {
  rentFormRef.value.resetFields()
  rentParams.value = { ...defaultRentParams }
  removeFile()
  dialogVisible.value = false
}
</script>

<template>
  <div class="park-enterprise-page">
    <!-- 搜索区域 -->
    <div class="search-container">
      <class style="width: 80px">企业名称:</class>
      <el-input
        v-model="params.name"
        placeholder="请输入企业名称"
        style="width: 220px; margin-right: 10px"
      ></el-input>
      <el-button type="primary" @click="onSearch">查询</el-button>
    </div>
    <!-- 按钮区域 -->
    <el-button
      type="primary"
      style="margin: 20px 0px"
      @click="$router.push('/patk/enterprise/add')"
      v-auth-btn="'park:enterprise:add_edit'"
      >添加企业</el-button
    >
    <!-- 表格区域 -->
    <el-table
      :data="enList"
      style="height: 400px"
      row-key="id"
      @expand-change="expandHandle"
    >
      <!-- 新增：展开部分 -->
      <el-table-column type="expand">
        <template #default="{ row }">
          <el-table :data="row.rentList">
            <el-table-column
              label="租赁楼宇"
              width="320"
              prop="buildingName"
              align="center"
            />
            <el-table-column
              label="租赁起始时间"
              prop="startTime"
              align="center"
            />
            <el-table-column label="合同状态" prop="status" align="center">
              <template #default="{ row }">
                <el-tag :type="formatTagType(row.status)">
                  {{ formatRentStatus(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" align="center">
              <template #default="{ row }">
                <el-button
                  size="small"
                  type="text"
                  @click="continueRent(row)"
                  :disabled="!row.renewFlag"
                  >续租</el-button
                >
                <!-- status === 3 为已退租，禁用退租按钮 -->
                <el-button
                  @click="outRent(row.id, row.enId)"
                  size="small"
                  type="text"
                  :disabled="!row.exitFlag"
                  >退租</el-button
                >
                <!-- status === 3 为已退租，可以删除 => !(row.status === 3) -->
                <el-button
                  @click="delRent(row.id, row.enId)"
                  size="small"
                  type="text"
                  :disabled="!(row.status > 1)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column label="序号" type="index" width="120" align="center" />
      <el-table-column
        label="企业名称"
        align="center"
        prop="name"
        width="320"
      />
      <el-table-column label="联系人" align="center" prop="contact" />
      <el-table-column label="联系电话" align="center" prop="contactNumber" />
      <el-table-column label="操作" align="center">
        <template #default="{ row }">
          <el-button type="text" @click="openRentDialog(row.id)"
            >添加合同</el-button
          >
          <el-button
            type="text"
            @click="
              $router.push({
                path: '/park/enterprise/detail',
                query: { id: row.id },
              })
            "
            >查看</el-button
          >
          <el-button
            type="text"
            @click="
              $router.push({
                path: '/patk/enterprise/add',
                query: { id: row.id },
              })
            "
            >编辑</el-button
          >
          <el-button type="text" @click="deleteEn(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <el-pagination
      v-model:current-page="params.page"
      :page-size="params.pageSize"
      layout="total, prev, pager, next, slot"
      :total="total"
      @current-change="handleCurrentChange"
    >
      <el-select
        style="width: 95px"
        v-model="params.pageSize"
        @change="changePageSize"
      >
        <el-option label="8条/页" :value="8"></el-option>
        <el-option label="10条/页" :value="10"></el-option>
        <el-option label="15条/页" :value="15"></el-option>
      </el-select>
    </el-pagination>
    <!-- 添加合同弹层 -->
    <el-dialog
      v-model="dialogVisible"
      :title="rentParams.type === 0 ? '添加合同' : '续约合同'"
      width="37%"
    >
      <el-form
        label-position="top"
        style="margin: 25px 80px 24px"
        :model="rentParams"
        :rules="rentRules"
        ref="rentFormRef"
      >
        <el-form-item label="租赁楼宇" prop="buildingId">
          <el-select
            placeholder="请选择租赁楼宇"
            v-model="rentParams.buildingId"
            :disabled="rentParams.type"
          >
            <el-option
              :label="item.name"
              :value="item.id"
              v-for="item in rentBuildingList"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="租赁起止日期" prop="dateList">
          <el-date-picker
            type="daterange"
            v-model="rentParams.dateList"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            range-separator="至"
            :disabled-date="disabledDate"
          />
        </el-form-item>
        <el-form-item label="租赁合同" prop="contractId">
          <el-upload
            ref="upload"
            action="#"
            :limit="1"
            :http-request="uploadRequest"
            :on-remove="removeFile"
          >
            <el-button type="primary" size="small">上传文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持扩展名：.doc .pdf, 文件大小不超过5M且
                <span style="color: red">只能选一个</span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <div style="width: 100%" class="btn">
            <el-button @click="rentDialogCancel">取消</el-button>
            <el-button type="primary" @click="rentDialogConfirm"
              >确定</el-button
            >
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
// 整个容器
.park-enterprise-page {
  padding: 20px;
  background-color: #fff;
}
// 搜索容器
.search-container {
  display: flex;
  align-items: center;
  padding-bottom: 20px;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
}
// 表格容器
.el-table {
  ::v-deep(.el-table__header th) {
    background-color: rgb(237, 237, 237, 0.9);
    color: rgb(43, 37, 37);
    padding: 10px 0;
  }
}
// 分页容器
.el-pagination {
  display: flex;
  justify-content: end;
  margin: 10px 0px;
}
// 按钮容器
.btn {
  display: flex;
  justify-content: flex-end;
}
</style>
